<!-- 角色权限分配弹窗 -->
<template>
  <ele-modal
    width="60%"
    title="分配权限"
    :visible="visible"
    @update:visible="updateVisible"
  >
    <!-- <el-scrollbar
      v-loading="authLoading"
      style="height: 60vh"
      wrap-style="overflow-x: hidden;"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="PC菜单权限管理" name="first"> -->
          <el-tree
          ref="tree"
          show-checkbox
          :data="authData"
          node-key="id"
          :default-expand-all="false"
          :props="{ label: 'title' }"
          @node-expand="handleExpand"
          :render-content="renderContent"
          :default-checked-keys="checkedKeys"
          >
          </el-tree>
        <!-- </el-tab-pane>
    </el-tabs>
    </el-scrollbar> -->
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save" v-show="isSave" >
        保存
      </el-button>
    </div>
  </ele-modal>
</template>

<script>
  import { UpdateURolemeun } from '@/api/usermanager/rolemanager';
  import { QueryALLMenuByRole } from '@/api/systemmanager/menumanager';
  
  export default {
    name: 'RoleAuth',
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 当前角色数据
      data: Object
    },
    data() {
      return {
        // 表格选中数据
        selection: [],
        // 是否展示保存
        isSave :true,
        // 权限数据
        authData: [],
        // 权限数据请求状态
        authLoading: false,
        // 提交状态
        loading: false,
        // 角色权限选中的keys
        checkedKeys: [],
        selectRows :[],
        appmenus:[],
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left',
            selectable: (row) => {
              return row.id !== undefined;
            }
          },
          {
            prop: 'menuName',
            label: '菜单名称',
            showOverflowTooltip: true,
          },
          {
            prop: 'menuUrl',
            label: '菜单地址',
            showOverflowTooltip: true,
            width: 260,
          },
          {
            prop: 'orderIndex',
            label: '菜单顺序',
            showOverflowTooltip: true,
          },
          {
            prop: 'menuTypeDesc',
            label: '菜单类型',
            showOverflowTooltip: true,
           
            align: 'center',
          }
        ],
      };
    },
    created(){
      
    },
    mounted() {
      this.changeCss();
    },
    methods: {
      /* 查询权限数据 */
      query() {
        this.authData = [];
        this.checkedKeys = [];
        if (!this.data) {
          return;
        }
    
        this.authLoading = true;
        QueryALLMenuByRole(this.data.id)
          .then((data) => {
            this.authLoading = false;
            // 转成树形结构的数据
            this.authData = this.$util.toTreeData({
              data: data,
              idKey: 'id',
              pidKey: 'parentId'
            });
            // 回显选中的数据
            const cks = [];
            this.$util.eachTreeData(this.authData, (d) => {
              if (d.ischecked && !d.children?.length) {
                cks.push(d.id);
              }
            });
            this.checkedKeys = cks;
          })
          .catch((e) => {
            this.authLoading = false;
            this.$message.error(e.message);
          });
      },


      /* 表格数据源 */
      async datasource(params) {
        params.where.roleid = this.data.id;
        this.appmenus = await QueryALLAppMenuByRole(params.where.roleid);
        return{ list:this.appmenus}
      },

      /* 保存权限分配 */
      save() {
        this.savePCRoleMenu();
      },

      //保存PC端角色菜单
      savePCRoleMenu(){
        this.loading = true;
        //获取选中的项
        const ids = this.$refs.tree
          .getCheckedKeys()
          .concat(this.$refs.tree.getHalfCheckedKeys());

        //更新角色菜单
        let rolemenus = [];
        if(ids){
          ids.map((i)=>{
              rolemenus.push({roleId:this.data.id,meunId:i})
          })
        }

        UpdateURolemeun(rolemenus)
        .then((msg) => {
          this.loading = false;
          this.$message.success(msg);
          this.updateVisible(false);
        })
        .catch((e) => {
          this.loading = false;
          this.$message.error(e.message);
        });
      },

      //选择行数据
      handleSelectionChange(val) {
        this.selectRows = [];
        val.map((p) => {
            this.selectRows.push(p.id);
        });
      },

      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      },
      handleExpand() {//节点被展开时触发的事件
			//因为该函数执行在renderContent函数之前，所以得加定时
      setTimeout(() => {
        this.changeCss();
      }, 10);
    },

    //树形节点中最后一级样式调整
    renderContent(h, { node, data, store }) {//树节点的内容区的渲染 Function
      let classname = "";
        // 由于项目中有三级菜单也有四级级菜单，就要在此做出判断
        if (data.menuType == 1) {
          classname = "foo";
        }
       
        return h(
          "p",
          {
            class: classname
          },
          node.label
        );
    },
    //修改最后一级样式
    changeCss() {
      var levelName = document.getElementsByClassName("foo"); // levelname是上面的最底层节点的名字
      for (var i = 0; i < levelName.length; i++) {
        // cssFloat 兼容 ie6-8  styleFloat 兼容ie9及标准浏览器
        levelName[i].parentNode.style.cssFloat = "left"; // 最底层的节点，包括多选框和名字都让他左浮动
        levelName[i].parentNode.style.styleFloat = "left";
        levelName[i].parentNode.onmouseover = function() {
          this.style.backgroundColor = "#fff";
        };
      }
    }
    },
    watch: {
      visible(visible) {
        this.isSave =this.data.code != 'JS00';
        if (visible) {
          this.query();
        }
      }
    }
  };
</script>
